<template>
  <div style="margin-right: 250px">
    <el-input style="width: 260px" v-model="username" placeholder="请输入用户名" clearable></el-input>
    <el-input style="width: 260px; margin-left: 10px" v-model="email" placeholder="请输入邮箱" clearable></el-input>
    <el-button style="margin-left: 10px" type="primary" @click="load"><el-icon><Search/></el-icon>查询</el-button>
    <el-button @click="handleAdd" type="primary"><el-icon><Plus/></el-icon>新增</el-button>
  </div>
  <el-table :data="state.tableData" stripe style="width: 100%">
    <el-table-column prop="id" label="ID" width="180" />
    <el-table-column prop="username" label="用户名" />
    <el-table-column prop="sex" label="性别" />
    <el-table-column prop="email" label="邮箱" />
    <el-table-column prop="address" label="地址" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleEdit(scope.row)"><el-icon><Edit /></el-icon>编辑</el-button>
        <el-popconfirm title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
          <template #reference>
            <el-button link type="danger" ><el-icon><Delete /></el-icon>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin: 10px 0">
    <el-pagination
        :background = "true"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        large
        :disabled="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="dialogFormVisible" title="用户信息" width="40%">
  <el-form :model="state.form" :rules="state.rules" ref="ruleFormRef" style="width: 85%" label-width="120px">
    <el-form-item label="用户名"  prop="username">
      <el-input v-model="state.form.username" autocomplete="off" placeholder="请输入用户名"/>
    </el-form-item>
    <el-form-item label="性别"  prop="sex">
<!--      <el-input v-model="state.form.sex" autocomplete="off" placeholder="请输入性别"/>-->
      <el-radio-group v-model="state.form.sex">
        <el-radio label="男" border>男</el-radio>
        <el-radio label="女" border>女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="邮箱"  prop="email">
      <el-input v-model="state.form.email" autocomplete="off" placeholder="请输入邮箱"/>
    </el-form-item>
    <el-form-item label="地址"  prop="address">
      <el-input type="textarea" v-model="state.form.address" autocomplete="off" placeholder="请输入地址"/>
    </el-form-item>
<!--    <el-form-item label="Zones" :label-width="formLabelWidth">-->
<!--      <el-select v-model="state.form.region" placeholder="Please select a zone">-->
<!--        <el-option label="Zone No.1" value="shanghai" />-->
<!--        <el-option label="Zone No.2" value="beijing" />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
  </el-form>
  <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </span>
  </template>
  </el-dialog>
</template>

<script setup>
  import {Edit, Delete, Plus, Search} from '@element-plus/icons-vue'
  import {getCurrentInstance, reactive, ref} from "vue";
  import request from "../request.js";
  import {ElMessage, ElNotification} from "element-plus";
  const {proxy} = getCurrentInstance()

  const checkEmail = (rule, value, callback) =>{
    console.log(value)
    if(!/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(value)){
      return callback(new Error('邮箱格式错误'))
    }
    callback()
  }
  const state = reactive({
    tableData:[],
    form:{},
    rules:{
      username:[
        {required:true, message:'请输入用户名', trigger:'blur'},
        {min:2, message: '最少输入两位', trigger:'blur'}
      ],
      address:[
        {required:true, message:'请输入地址', trigger:'blur'},
        {max:255, message: '最多255个字符', trigger:'blur'}
      ],
      email:[
        { validator: checkEmail, trigger: 'blur'}
      ]
    }
  })

  const currentPage = ref(1)
  const pageSize = ref(1)
  const total = ref(0)
  const username = ref('')
  const email = ref('')

  const load = () =>{
    request.get("/user/page", {
      params:{
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        username: username.value,
        email: email.value
      }
    }).then(res => {
      if(res.code==='200'){
        state.tableData = res.data.list
        total.value = res.data.total
        // console.log(total.value)
      }
    })
  }
  load()

  const handleSizeChange = (val) => {
    pageSize.value = val
    load()
  }
  const handleCurrentChange = (val) => {
    currentPage.value = val
    load()
  }

  const dialogFormVisible = ref(false)
  const handleAdd = () => {
    dialogFormVisible.value = true
    state.form = {} //初始化数据
  }

  const handleEdit = (row) => {
    dialogFormVisible.value = true
    state.form = JSON.parse(JSON.stringify(row))
  }

  const save = () => {
    proxy.$refs.ruleFormRef.validate((valid) => {
      if(valid){
        //console.log(state.form)
        if(state.form.id){//id存在为编辑
          request.put("/user", state.form).then(res => {
            if(res.code==='200'){
              ElNotification({
                type:'success',
                message:'保存成功'
              })
              dialogFormVisible.value = false
              load()
            }else{
              ElNotification.error(res.msg);
            }
          })
        }else{//新增
          state.form.password = "123"
          request.post("/user", state.form).then(res => {
            if(res.code=='200'){
              ElNotification({
                type:'success',
                message:'保存成功'
              })
              dialogFormVisible.value = false
              load()
            }else{
              ElMessage.error(res.msg);
            }
          })
        }
      }
    })
  }

  const handleDelete = (id) => {
    request.delete("/user/" + id).then(res => {
      if(res.code==='200'&&res.data) {
        ElNotification.success("删除成功")
      }else{
        ElMessage.error("删除失败")
      }
      load()
    })
  }



</script>